package com.pignest.hotel.ui.member;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Button;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.IntegralLog;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.MemberLevel;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.UIUtils;

public class UpgradeWindow extends Window implements EventListener {

	/**
	 * 会员升级
	 */
	private static final long serialVersionUID = -5854113353799282624L;
	private MemberService memberService;
	private Member member;
	private MemberLevel curLevel;
	
	private Textbox priceTextbox;
	
	private Listbox chargeTypeListbox;
	
	private Textbox remarkTextbox;
	private Label namelabel;
	private Label levelLabel;
	private Label mobileLabel;
	private Label sexLabel;
	//private Label memberTypeLabel;
	private Label stateLabel;
	//private Label registModeLabel;
	private Label creditLabel;
	private Label integralLabel;
	private Label balanceLabel;
	private Label used;
	private Label dealTime;
	
	private Listbox memberLevelListbox;
	private Label levelpriceTextbox;
	private Intbox integralTextbox;
	
	private Label prompting;
	
	private Button buyBtn;
	private Button integralBtn;
	//private Button grantBtn;
	private Listbox chargeListbox;
	private Listbox integralListbox;
	
	private Tab chargeTab;
	private Tab interalTab;
	
	
	public UpgradeWindow(){
		memberService = Services.getMemberService();
		addEventListener("onCreate", this);
		
	}
	
	@Override
	public void onEvent(Event event) throws Exception {
		// TODO Auto-generated method stub
		if ("onCreate".equals(event.getName())) {
			namelabel=(Label)getFellow("name");
			levelLabel=(Label)getFellow("level");
			mobileLabel =(Label)getFellow("mobile");
			sexLabel=(Label)getFellow("sex");
			//memberTypeLabel=(Label)getFellow("memberType");
			stateLabel=(Label)getFellow("state");
			//registModeLabel=(Label)getFellow("registMode");
			creditLabel =(Label)getFellow("credit");
			integralLabel=(Label)getFellow("integral");
			balanceLabel=(Label)getFellow("balance");
			priceTextbox=(Textbox)getFellow("priceTextbox");
			chargeTypeListbox=(Listbox)getFellow("chargeTypeListbox");
			remarkTextbox=(Textbox)getFellow("remarkTextbox");
			used =(Label)getFellow("used");
			dealTime=(Label)getFellow("dealTime");
			memberLevelListbox=(Listbox)getFellow("memberLevelListbox");
			levelpriceTextbox=(Label)getFellow("levelpriceTextbox");
			integralTextbox=(Intbox)getFellow("integralTextbox");
			prompting =(Label)getFellow("prompting");
			
			buyBtn=(Button)getFellow("buyBtn");
			integralBtn=(Button)getFellow("integralBtn");
			//grantBtn=(Button)getFellow("grantBtn");
			chargeListbox=(Listbox)getFellow("chargeListbox");
			integralListbox=(Listbox)getFellow("integralListbox");
			
			chargeTab =(Tab)getFellow("chargeTab");
			interalTab=(Tab)getFellow("interalTab");
			
			setValue();
			queryChargeList();
			queryIntegral();
			selectLevel();
		}
	}
	public void setValue(){
		if(this.member!=null){
		   namelabel.setValue(this.member.getName());
		   if(this.member.getMemberLevel()!=null)
		       levelLabel.setValue(this.member.getMemberLevel().getMemberlevel());
		   else
			   levelLabel.setValue("");
		   mobileLabel.setValue(this.member.getMobile());
		   sexLabel.setValue(this.member.getSex());
		   //memberTypeLabel.setValue(this.member.getType());
		   stateLabel.setValue(memberService.queryCardState(member));
		   //registModeLabel.setValue(this.member.getRegisterMode());
		   Integer credit =this.member.getCredit();
		   if(credit!=null)
		      creditLabel.setValue(credit.toString());
		   Integer intgral =this.member.getIntegral();
		   if(intgral!=null)
		     integralLabel.setValue(intgral.toString());
		   Integer balance= this.member.getBalance();
		   if(balance!=null)
		     balanceLabel.setValue(Utils.toPrice(balance));
		   int iUsed =memberService.countMemberHistoryUsed(member, true);
		   used.setValue(Utils.toPrice(iUsed));
		   dealTime.setValue(DateUtil.toString(member.getDealTime(), DateUtil.DEFAULT_TIME_FORMAT));
		}
	}
	public void changeValue(){
		if(this.member!=null){
			if(this.member.getMemberLevel()!=null)
			       levelLabel.setValue(this.member.getMemberLevel().getMemberlevel());
			   else
				   levelLabel.setValue("");
			 Integer credit =this.member.getCredit();
			   if(credit!=null)
			      creditLabel.setValue(credit.toString());
			   Integer intgral =this.member.getIntegral();
			   if(intgral!=null)
			     integralLabel.setValue(intgral.toString());
			   Integer balance= this.member.getBalance();
			   if(balance!=null)
			     balanceLabel.setValue(Utils.toPrice(balance));
			   selectLevel();
			   queryChargeList();
			   queryIntegral();
		}
	}
	public String charge(){
		try{
            if(this.member==null){
            	return "无效的会员！";
            }
			String price =priceTextbox.getValue();
			if(!Utils.checkPrice(price))
			{
				return "请输入合法值，非负数,小数不能超过2位";
			}		
			String chargetype =UIUtils.getSelectedValue(chargeTypeListbox);
			String remark =remarkTextbox.getValue();
			Memberchargehistrory ms = new Memberchargehistrory();
			ms.setMember(this.member);
			ms.setChargeTime(new Date());
			ms.setChargetype(chargetype);
			ms.setPrice(Utils.toPrice(price));
			ms.setOptype("充值");
			ms.setRemark(remark);
			this.member=memberService.chargeMember(ms);
			balanceLabel.setValue(Utils.toPrice(this.member.getBalance()));
			queryChargeList();
			return "";
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
    public void setMeber(String id){
    	Member member = memberService.getMember(id);
    	this.member=member;
    }
    public void queryChargeList(){
    	chargeListbox.getItems().clear();
    	List <Memberchargehistrory> history=memberService.queryHistory(this.member);
    	for(Memberchargehistrory h:history){
    		Listitem listitem = new Listitem();
	    	listitem.setParent(chargeListbox);
	    	listitem.appendChild(new Listcell(h.getChargetype()));
	    	listitem.appendChild(new Listcell(ChargeOpType.valueOf(h.getOptype()).getValue()));
	    	listitem.appendChild(new Listcell(Utils.toPrice(h.getPrice())));
	    	listitem.appendChild(new Listcell(DateUtil.toFullString(h.getChargeTime())));
	    	listitem.appendChild(new Listcell(h.getRemark()));
    	}
    	
    }
    public void queryIntegral(){
    	integralListbox.getItems().clear();
    	List<IntegralLog> ilog =memberService.queryIntegral(this.member);
    	for(IntegralLog h:ilog){
    		Listitem listitem = new Listitem();
	    	listitem.setParent(integralListbox);
	    	listitem.appendChild(new Listcell(h.getType()));
	    	Integer i =h.getIntegral();
	    	if(i!=null)
	    	    listitem.appendChild(new Listcell(String.valueOf(i)));
	    	else
	    		listitem.appendChild(new Listcell("0"));
	    	listitem.appendChild(new Listcell(DateUtil.toFullString(h.getTime())));
	    	listitem.appendChild(new Listcell(h.getRemark()));
    	}
    }
    /**
     * 选择新会员等级
     * 描述：
     * 如果选择的会员等级比当前的会员等级低则不能升级
     * */
    public void selectLevel(){
    	String classId= UIUtils.getSelectedValue(memberLevelListbox);
    	curLevel= memberService.getMemberLevel(classId);
    	
    	boolean isUp=memberService.isLevelUp(member, curLevel);
    	if(isUp)
    	{
    		buyBtn.setDisabled(false);
    		integralBtn.setDisabled(false);
    		//grantBtn.setDisabled(false);
    		levelpriceTextbox.setValue(Utils.toPrice(curLevel.getLevelPrice()));
    		integralTextbox.setValue(curLevel.getLevelIntegal());
    		prompting.setValue("OK！");
    	}else{
    		buyBtn.setDisabled(true);
    		integralBtn.setDisabled(true);
    		//grantBtn.setDisabled(true);
    		prompting.setValue("选择的等级过低或者同等级！");
    		levelpriceTextbox.setValue(Utils.toPrice(curLevel.getLevelPrice()));
    		integralTextbox.setValue(curLevel.getLevelIntegal());
    	}
    		
    }
    public boolean contrlBtn(String type){
    	//String classId= UIUtils.getSelectedValue(memberLevelListbox);
    	//MemberLevel level =memberService.getMemberLevel(classId);
    	
    	if(type.equals("购买")){//如果是购买升级则进行计算充值+余额不能小于升级所需要的费用
    		String recharge=priceTextbox.getValue();
    		int balance =member.getBalance();
    		int h=Utils.toPrice(recharge)+balance;
    		int i=h-curLevel.getLevelPrice();
    		if(i<0){
    			if(UIUtils.confirm("余额不够是否要继续升级!")){
    				return true;
    			}else{
    				prompting.setValue("余额不够!"+Utils.toPrice(i)+",请充值！");
    				return false;
    			}
    				
    		}
    	}
    	if(type.equals("积分")){
    		int integral =member.getIntegral();//目前积分
    		if(curLevel.getLevelIntegal()>integral){
    			
    			if(UIUtils.confirm("积分不够是否要继续升级!")){
    				return true;
    			}else{
    				prompting.setValue("积分不够!");
    				return false;
    			}
    		}
    	}
    	if(type.equals("授权")){
    		return true;
    	}
    	return true;
    }
    public boolean buy(){
     try{
    		if(!Hotel.onDuty()){
    			UIUtils.alert("未在值班不能操作此业务!");
    			return false;
    		}
    	if(contrlBtn("购买")){
    		
			String recharge=priceTextbox.getValue();
			String chargeType=UIUtils.getSelectedValue(chargeTypeListbox);
			Memberchargehistrory rechargeMs = new Memberchargehistrory();
			if(recharge!=null&&!recharge.equals("0")){
				
				rechargeMs.setMember(this.member);
				rechargeMs.setChargeTime(new Date());
				rechargeMs.setChargetype(chargeType);
				rechargeMs.setPrice(Utils.toPrice(recharge));
				rechargeMs.setOptype(ChargeOpType.OnCharge.name());
				rechargeMs.setRemark("升级会员卡时充值"+Utils.toPrice(rechargeMs.getPrice()));
				//memberService.chargeMember(rechargeMs);
			}
			this.member.setMemberLevel(curLevel);
			this.member=memberService.buyUpLevel(this.member,rechargeMs);
			changeValue();
			chargeTab.setSelected(true);
			return true;
      }else{
    	  return false;
      }
    	}catch(Exception e){
    		e.printStackTrace();
    		prompting.setValue("异常："+e.getMessage());
    		return false;
    	}
    }
    public boolean integralUp(){
    	try{
    		if(contrlBtn("积分")){
    			IntegralLog log = new IntegralLog();
    			log.setMember(this.member);
    			log.setTime(new Date());
    			log.setType("升级");
    			log.setIntegral(-curLevel.getLevelIntegal());
    			log.setRemark("卡升级所扣除积分"+curLevel.getLevelIntegal());
    			this.member.setMemberLevel(curLevel);
    			this.member=memberService.integralUpLevel(this.member, log);
    			changeValue();
    			interalTab.setSelected(true);
    		}else{
    			return false;
    		}
    		return true;
    	}catch(Exception e){
    		e.printStackTrace();
    		return false;
    	}
    }
}
